package com.xxx.controller;

import com.xxx.common.AppResult;
import com.xxx.common.ResultCode;
import com.xxx.config.AppConfig;
import com.xxx.exception.ApplicationException;
import com.xxx.model.User;
import com.xxx.services.IUserService;
import com.xxx.utils.MD5Util;
import com.xxx.utils.StringUtil;
import com.xxx.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;


    @PostMapping("/registry")
    @ApiOperation("用户注册")
    public AppResult registry(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //校验密码和重复密码是否相同
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtil.UUID_32();
        String ciphertext = MD5Util.md5Salt(password, salt);
        user.setPassword(ciphertext);
        user.setSalt(salt);

        //调用service层
        userService.createNormalUser(user);
        return AppResult.success();
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + "username = " + username);
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //登录成功保存session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success();
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @param id
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        //如果id为空, 从session中获取信息
        if (id == null) {
            HttpSession session = request.getSession(false);//如果没有session, 不主动创建
            User sessionUser = (User) session.getAttribute(AppConfig.USER_SESSION);
            user = userService.selectById(sessionUser.getId());
        } else {
            //如果id不为空, 从数据库中根据id查询
            user = userService.selectById(id);
            log.info("user"+ user);
        }
        //判断user是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("退出成功");
            //销毁session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 更新个人信息
     *
     * @param username
     * @param nickname
     * @param gender
     * @param email
     * @param phoneNum
     * @param remark
     * @return
     */
    @ApiOperation("更新个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username", required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                @ApiParam("电话号") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname) && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark) && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }
        HttpSession session = request.getSession(false);//如果没有session, 不主动创建
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);
//        //将修改后的值存在session中, 防止前端拿不到更新后的数据
//        user = userService.selectById(user.getId());
//        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (!newPassword.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session = request.getSession(false);//如果没有session, 不主动创建
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        return AppResult.success();
    }
}
